package com.gin.no_gay_alliance.utils;

import android.Manifest;
import android.content.pm.PackageManager;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

/**
 * 权限工具
 *
 * @author : ginstone
 * @version : v1.0.0
 * @since : 2023/7/4 15:56
 **/
public class PermissionUtils {
    /**
     * 检查是否持有给定的所有权限，如果有任一未持有则弹窗请求授权
     *
     * @param activityCompat {@link AppCompatActivity}
     * @param requestCode    请求code
     * @param permissions    权限 从{@link Manifest.permission} 下选择
     * @return 当前是否持有所有权限
     */
    public static boolean checkPermissions(AppCompatActivity activityCompat, int requestCode, String... permissions) {
        if (permissions == null) {
            return false;
        }
        if (!hasPermissions(activityCompat, permissions)) {
            activityCompat.requestPermissions(permissions, requestCode);
            return false;
        }
        return true;
    }

    /**
     * 判断当前是否持有给定的所有权限
     *
     * @param activityCompat {@link AppCompatActivity}
     * @param permissions    权限
     * @return 是否持有所有权限
     */
    public static boolean hasPermissions(AppCompatActivity activityCompat, String... permissions) {
        if (permissions == null) {
            return false;
        }
        for (String permission : permissions) {
            if (activityCompat.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    /**
     * 判断授权结果是否为全部授权
     *
     * @param grantResults 授权结果
     * @return 判断授权结果是否为全部授权
     */
    public static boolean hasPermissions(@NonNull int[] grantResults) {
        for (int grantResult : grantResults) {
            if (grantResult != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }
}
